package com.sinosoft.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sinosoft.gateway.config.Constants;
import com.sinosoft.gateway.model.RequestMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.annotation.Contract;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class RouterFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }
    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI().toLowerCase();
        log.info("RouterFilter debug requestURI:{}", requestURI);

        // 拦截特定的请求重新构造httpRequest
        if(pathMatcher.match("/debug", requestURI) && request.getMethod().equalsIgnoreCase("POST")){
            ctx.addZuulRequestHeader("EXEXXX", "NEXT");
            ctx.put(Constants.IS_DEBUG_REQUEST_FLAG, true);
            String requestBody = null;
            try {
                requestBody = IOUtils.toString(request.getInputStream(), "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(StringUtils.isEmpty(requestBody)){
                return null;
            }
            RequestMessage requestMessage = JSON.parseObject(requestBody, RequestMessage.class);
            log.info("requestMessage:{}", requestMessage);
//             requestMessage.getUrl();
            if(requestMessage.getHeader() != null){
                for(Map.Entry<String, String> entry : requestMessage.getHeader().entrySet()){
                    ctx.addZuulRequestHeader(entry.getKey(), entry.getValue());
                }
            }
            ctx.put("exec.requestBody", requestMessage);
        }
        return null;
    }
}
